/*
* Copyright (c) 2011
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of the License "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
*
* Contributors:
*
* Description: 
*
*/

#include <QtGui>
#include <QtNetwork>


#include "WirelessRemote.h"
#include "WirelessSearch.h"

#if defined Q_OS_SYMBIAN
#define ROKUSETTINGSFILE "C:\\data\\wirelessremotesettings.txt"
#elif defined  QT_SIMULATOR || defined WIN32
#define ROKUSETTINGSFILE "C:\\wirelessremotesettings.txt"
#elif Q-WS-MAEMO-5
#define ROKUSETTINGSFILE "/tmp/wirelessremotesettings.txt"
#else
#error unspecified os build
#endif


WirelessRemote::WirelessRemote(QWidget *parent)
    : QDialog(parent)
{

    ui.setupUi(this);

//#if Q-WS-MAEMO-5
 //       resize(640, 360);
 //       setLandscapeOrientation(); // N900 in landscape only
//#endif
	tcpSocket = new QTcpSocket(this);

        // find out which IP to connect to
        ipAddress = getStoredIpAddress();
        if (ipAddress == NULL){
            // use IPv4 localhost
            ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
            saveIpAddress(ipAddress);
            ipAddress = getStoredIpAddress();
        }

        ui.rokuIPLabel->setText("DVP Address: " + ipAddress);

        connect(ui.searchButton, SIGNAL(clicked()),
                    this, SLOT(searchRequest()));

        
        connect(ui.exitButton, SIGNAL(clicked()),
                    this, SLOT(exitRequest()));

        connect(ui.aboutButton, SIGNAL(clicked()),
                    this, SLOT(aboutRequest()));

        connect(ui.helpButton, SIGNAL(clicked()),
                    this, SLOT(helpRequest()));

        connect(ui.settingsButton, SIGNAL(clicked()),
                    this, SLOT(settingsRequest()));

        connect(ui.forwardButton, SIGNAL(clicked()),
                    this, SLOT(forwardRequest()));

        connect(ui.backButton, SIGNAL(clicked()),
                    this, SLOT(backRequest()));

        connect(ui.pausePlayButton, SIGNAL(clicked()),
                    this, SLOT(playPauseRequest()));

        connect(ui.downButton, SIGNAL(clicked()),
	            this, SLOT(downRequest()));
        connect(ui.upButton, SIGNAL(clicked()),
                    this, SLOT(upRequest()));
        connect(ui.leftButton, SIGNAL(clicked()),
                    this, SLOT(leftRequest()));
        connect(ui.rightButton, SIGNAL(clicked()),
                    this, SLOT(rightRequest()));
        connect(ui.homeButton, SIGNAL(clicked()),
                    this, SLOT(homeRequest()));
        connect(ui.selectButton, SIGNAL(clicked()),
                    this, SLOT(selectRequest()));
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(doRokuCommand()));
        connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
                this, SLOT(displayError(QAbstractSocket::SocketError)));

}

WirelessRemote::~WirelessRemote()
{

}

void WirelessRemote::downRequest(){
    this->rokuCommand = "\npress down\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::upRequest(){
    this->rokuCommand = "\npress up\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::leftRequest(){
    this->rokuCommand = "\npress left\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::rightRequest(){
    this->rokuCommand = "\npress right\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::selectRequest(){
    this->rokuCommand = "\npress select\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::homeRequest(){
    this->rokuCommand = "\npress home\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::playPauseRequest(){
    this->rokuCommand = "\npress pause\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::backRequest(){
    this->rokuCommand = "\npress back\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::forwardRequest(){
    this->rokuCommand = "\npress fwd\n";
    sendRokuCommand(rokuCommand);
}

void WirelessRemote::sendRokuCommand(QString command){

    rokuCommand = command;
	
    tcpSocket->abort();
   // QString test = ui.ipEdit->toPlainText();
    // int portID = ui.portEdit->toPlainText().toInt();
    tcpSocket->connectToHost(ipAddress, 8080);
    //tcpSocket->connectToHost("192.168.1.66", 8080);
	 
}

void WirelessRemote::doRokuCommand()
{

    QDataStream in(tcpSocket);
    in.setVersion(QDataStream::Qt_4_0);

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);

    out << rokuCommand.toAscii();
    out.device()->seek(0);

    qint64 bytesWritten =  tcpSocket->write(block);
    tcpSocket->disconnectFromHost();

}

void WirelessRemote::displayError(QAbstractSocket::SocketError socketError)
{
    switch (socketError) {
    case QAbstractSocket::RemoteHostClosedError:
        break;
    case QAbstractSocket::HostNotFoundError:
        QMessageBox::information(this, tr("Wireless Remote"),
                                 tr("The host was not found. Please check the "
                                    "host name setting."));
        break;
    case QAbstractSocket::ConnectionRefusedError:
        QMessageBox::information(this, tr("Wireless Remote"),
                                 tr("The connection was refused by the peer. "
                                    "Make sure that your Roku device is running, "
                                    "and check that the host name "
                                    "is correct."));
        break;
    default:
        QMessageBox::information(this, tr("Wireless Remote"),
                                 tr("The following error occurred: %1.")
                                 .arg(tcpSocket->errorString()));
    }

}

QString WirelessRemote::getStoredIpAddress()
{
    //Try to read the file. Return null if it does not exist
    QFile file(ROKUSETTINGSFILE);
    file.open(QIODevice::Text | QIODevice::ReadOnly);
    QTextStream in(&file);
    QByteArray fileContents = file.readAll();
    QString ipFromFile = QString(fileContents);
    if (ipFromFile != NULL && ipFromFile.size() > 0){
        return ipFromFile;
    }
    file.close();

    return NULL; // File not found, user must add ipaddress

}

void WirelessRemote::saveIpAddress(QString ip)
{
    //Try to read the file. Return null if it does not exist
    QFile file(ROKUSETTINGSFILE);
    file.open(QIODevice::Text | QIODevice::WriteOnly | QIODevice::Truncate);
    QTextStream out(&file);
    out  << ip;
    file.close();
}

void WirelessRemote::settingsRequest(){
    bool ok;
    QString ip = QInputDialog::getText(this, "Roku IP Address", "Roku IP Address", QLineEdit::Normal, ipAddress, &ok);
    if (ok && ip != ipAddress){
        this->ipAddress = ip;
        ui.rokuIPLabel->setText("Roku Address: " + ipAddress);
        saveIpAddress(ip);
    }
}

void WirelessRemote::aboutRequest(){
    QMessageBox::information(this, tr("DVP Remote"),
                             tr("Wireless Remote (C) 2011 Tim Kelly. Source code distributed under EPL."));
}

void WirelessRemote::helpRequest(){
    QMessageBox::information(this, tr("DVP Remote"),
                             tr("Set your DVP IP address in the Settings and make sure WIFI is working on your device."));
}

void WirelessRemote::exitRequest(){
    QApplication::exit();
}

void WirelessRemote::searchRequest(){
    WirelessSearch s(this);
    s.showFullScreen();
    s.exec();
}

void WirelessRemote::resizeEvent(QResizeEvent* event){
//    QSize widgetSize = event->size();
//    if (widgetSize.height() > widgetSize.width()){
//    	// portrait
//    	// info buttons
//    	ui.settingsButton->setGeometry(QRect(10, 510, 100, 61));
//    	ui.helpButton->setGeometry(QRect(130, 510, 100, 61));
//    	ui.aboutButton->setGeometry(QRect(250, 510, 100, 61));

//    	// player controls
//        ui.backButton->setGeometry(QRect(27, 340, 81, 91));
//        ui.pausePlayButton->setGeometry(QRect(120, 340, 121, 91));
//        ui.forwardButton->setGeometry(QRect(252, 340, 81, 91));

//        ui.rokuIPLabel->setGeometry(QRect(10, 590, 301, 41));
//        ui.exitButton->setGeometry(QRect(305, 585, 51, 51));

//    } else {
//        // landscape
//       // setLandscapeOrientation();
        
//    }
    QDialog::resizeEvent(event);
}

void WirelessRemote::setLandscapeOrientation(){
    // info buttons
    ui.settingsButton->setGeometry(QRect(510, 60, 100, 61));
    ui.aboutButton->setGeometry(QRect(510, 135, 100, 61));
    ui.helpButton->setGeometry(QRect(510, 210, 100, 61));

    // player controls
    ui.backButton->setGeometry(QRect(380, 27, 80, 91));
    ui.pausePlayButton->setGeometry(QRect(360, 120, 121, 91));
    ui.forwardButton->setGeometry(QRect(380, 211, 80, 91));

    ui.rokuIPLabel->setGeometry(QRect(10, 310, 301, 41));
    ui.exitButton->setGeometry(QRect(585, 2, 51, 51));
}

